// 定义这个组件为 app 层级 将框架文件进行挂载处理
// import { Cloud } from '@tbmp/mp-cloud-sdk';
import { Cloud } from '@ym_interaction/mp-cloud-sdk'; // 没有请求时在控制台打印的 console
import Mfutil from '../utils/mfutil/index';
import config from '../config';
import httpRequest from '../lib/httpRequest';
import navigateTo from '../lib/navigateTo';
import publicTrack from '../lib/publicTrack';


//将路由跳转方法挂载在全局
$global.navigateTo = navigateTo;
import Common from '../lib/common.js';
const keys = ['wildwood_config_flash_coupon_event']
const cloud = new Cloud();
// 云应用初始化   
cloud.init({
    env: 'online',
});
const mfutil = new Mfutil({ config });
mfutil.init({ cloud });
$global.cloud = cloud;

$global.mfutil = mfutil;
//将api请求 挂载在全局中（云函数，云应用:业务请求、埋点请求）
$global.httpRequest = httpRequest;
//埋点请求挂载在全局
$global.publicTrack = publicTrack;
// 机型信息--
$global.systemInfo = {}
// 配置信息初始化
$global.config = {
    constraintSellerId: false,         // 是否强制使用模拟的店铺ID
    mySellerId: '',         // 模拟的店铺ID  耐克： 890482188  jordan: 3327042818   kids: 3728394127  
    cloudName: 'daily_morefun',       // 云函数请求名 : ' daily_morefun '，' morefun '   
    cloudAppId: '35796',              // 云应用 id : '32193 ', ' 35796 ', ' 37798 '
    baseUrl: 'https://tmall-static-test.nike.com.cn/wildwood_phase14/couponModel',      // 公共基础地址
    baseAvatarUrl: 'https://tmall-static-test.nike.com.cn/avatar/',      // 公共基础地址
    // baseUrl: 'https://tmall-origin-static.nike.com.cn/wildwood_phase13/',      // 公共基础地址:online
    // baseAvatarUrl: 'https://tmall-origin-static.nike.com.cn/avatar/',      // 公共基础地址:online
    trackEnv: 'test',                 // 埋点请求环境 : ' test ', ' production ' 
    trackVersion: '1.7.3',            // 埋点版本号CNY:1.0.0 SBD:1.1.0   phase8：1.2.0   'sbw':1.3.0  D11: 1.4.0  2024CNY:1.5.0   2024SBD:1.6.0 2024618:1.7.0
    traceId: '',                      // 埋点请求的 traceId
    shopInfo: {},                     // 通过云函数查询到的，当前配置的店铺相关信息
}

// 处理 traceId 这个方法需要确认
let conf = '0123456789abcdef', traceId = '';
for (let i = 0; i < 16; i++) {
    let c = Math.floor(Math.random() * 16)
    traceId = traceId + conf[c]
}
$global.config.traceId = traceId;
Component({
    data: {
        isShow:false,
        pageindex: 2,
        mfutil: {},
        baseUrl:$global.config.baseUrl,
        couponData: [],
        initActiveIndex: null,
        activeCoupon:{}
    },
    // 初始化
    onInit () {
        my.mfutil = mfutil;
        mfutil.onAppInit();
            //获取手机机型
        Common.getSystemInfo()
    },
    async didMount () {
        my.setGestureMode({ "gestureMode": "inner" });
        await this.getShopInfo()
        await this.initPage()
        this.setData({
          isShow:true
        })
        
    },
    methods: {
        // 获取莫凡实例化相关信息
        async getShopInfo () {
            // 获取店铺 ID
            const sellerId = await Common.getSellerId();
            // 打印
            $global.mfutil.logger.log(sellerId, 'sellerId');
            // 获取店铺实例化信息
            await $global.httpRequest.getShopInfo(sellerId);
        },
        async initPage () {
          try {
            const { data: { wildwood_config_flash_coupon_event } } = await $global.httpRequest.getConfigsInfo(keys);
            console.log(wildwood_config_flash_coupon_event,'====wildwood_config_flash_coupon_event')
              if (wildwood_config_flash_coupon_event.length <= 0) return
              const { time } = await my.getServerTime();
              // 获取店铺实例化信息
              const activeCoupon = wildwood_config_flash_coupon_event.find((item) => (
                time >= new Date(item.start_time).getTime() 
                && time <= new Date(item.end_time).getTime() 
                && item.is_active == 1 
                && item.is_deleted == 0
                ))
                if(!activeCoupon)return
                if(activeCoupon.name.trim().length > 9){
                  activeCoupon.name = activeCoupon.name.substring(0,10+activeCoupon.name.split(' ').length-1)
                }
                activeCoupon.name  = this.moduleNameHandle(activeCoupon.name)
                  const couponData = activeCoupon.coupon_list.filter((i) => {
                  let hours = new Date(i.flash_start_time).getHours();
                  let minutes = new Date(i.flash_start_time).getMinutes();
                  hours = hours < 10 ? "0" + hours : hours;
                  minutes = minutes < 10 ? "0" + minutes : minutes;
                  i.time = hours + ':' + minutes;
                  i.autoplay = false;
                  return ((i.shop_id === $global.shopInfo.shopId) && new Date(i.flash_start_time) >= new Date().setHours(0, 0, 0, 0) && 
                  new Date(i.flash_start_time) <= new Date().setHours(23, 59, 59, 999))
              })
              if(couponData.length > 0 ){
                couponData.sort((a,b)=>{return new Date(a.flash_start_time).getTime() - new Date(b.flash_start_time).getTime()})
              }
              // 初始化高亮时间
              const initActiveIndex = await this.initActive(couponData)
              if(initActiveIndex){
                 couponData[initActiveIndex].autoplay=true
              }
             this.setData({
                 couponData,
                 activeCoupon,
                 initActiveIndex
             })
         } catch (error) {
             this.setData({
                 couponData: []
             })
             console.log('闪购券数据异常', error)
         }
      },
       // 处理模块标题
       moduleNameHandle(moduleName=''){
        let newName = ''
        let tName = 0;  //空格数
        console.log(moduleName,'======moduleName')
        for(let i = 0;i < moduleName.length;i++){
           if(newName.length - tName >= 10)break
           if(/^\s*$/.test(moduleName[i])){
             if(tName < 2){
               tName++;
               newName+=moduleName[i]
             }else{
               continue
             }
           }else{
               newName+=moduleName[i]
           }
        }
        console.log(newName,'=====newName')
        return newName
     },
      // 选出活跃时间
      async initActive (couponData) {
          try {
              const { time } = await my.getServerTime();// 当前时间
              let { initActiveIndex = 0 } = this.data;
              if (couponData.length < 1) return
              const forceJumpIndex = await couponData.findIndex((item) => (item.is_force_jump));
                  let activeList = await couponData.filter((item) => (time >= new Date(item.flash_start_time).getTime()));
                  let closest = activeList.length > 0 ? activeList[0] : couponData[0];
                  initActiveIndex = couponData.findIndex((item) => (item.id == closest.id))
                  for (let i = 0; i < activeList.length; i++) {
                      const item = activeList[i];
                      const diff = Math.abs(new Date(item.flash_start_time).getTime() - time); // 计算与当前时间的差距
                      if (diff < Math.abs(new Date(closest.flash_start_time).getTime() - time) && time >= new Date(item.flash_start_time).getTime()) {
                          closest = item; // 更新最接近的元素
                          // initActiveIndex = i;
                          initActiveIndex = couponData.findIndex((i) => (i.id == item.id))
                      }
                  }
                  if(forceJumpIndex > initActiveIndex){
                    initActiveIndex = forceJumpIndex;
                  }
              return initActiveIndex; // 返回最接近的元素
          } catch (err) {
              console.log(err, '========initActiveIndex')
          }
      },
      moveSwiper (params) {
          const {activeCoupon,couponData} = this.data;
          $global.mfutil.emitter.emit('moveCouponSwiper', params)
          $global.mfutil.emitter.emit('moveTimeSwiper', params)
          this.publicTrack('wildwoodwidget:flash_coupon_click',{
            event_id:activeCoupon.id,
            tab_time:couponData[params.nextactiveIndex].flash_start_time,
            type: 'tab',
            source:'tmall_page'
          })
      },
      publicTrack (event, data = {}) {
          const params = {
              event,
              name: "widget_flash_coupon",
              // member_type: ($global.userInfo && $global.userInfo.avatar_type != 'OLD') ? 'wildwood_member' : 'store_member',
              // member_type: ($global.userInfo && $global.userInfo.avatar_id != 0 ) ? 'wildwood_member' : 'store_member',
              data,
              sort_order: 0,
          }
          $global.publicTrack(params);
      },
    }
});

